package com.ry.BondUnpack;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Server2 {

    public static void main(String[] args) {
        Server2 server2 = new Server2();
        try {
            server2.server(8080);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public void server(int port) throws InterruptedException {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup child = new NioEventLoopGroup(1024);
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, child)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
//                        ch.pipeline().addLast("frameDecoder",new LineBasedFrameDecoder(80));
//                        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024));
//                        ch.pipeline().addLast("stringDecoder",new StringDecoder());
//                        ch.pipeline().addLast("stringEncoder",new StringEncoder());

                        ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new ServerHandler());
                    }
                });

        ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
        channelFuture.channel().closeFuture().sync();
    }


    class ServerHandler extends ChannelInboundHandlerAdapter {
        int a = 0;

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            a++;
//            ByteBuf byteBuf = (ByteBuf) msg;
//            byte[] bb = new byte[byteBuf.readableBytes()];
//            byteBuf.readBytes(bb);
//            try {
//                String str = new String(bb, "UTF-8");
//                System.out.println(a + "-" + str);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            System.out.println(a +"："+ msg);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
        }
    }
}
